# -*- coding: utf-8 -*-
# Create your views here.
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import Group
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from main.forms import RestApplayForm
from main.models import Rest_apply
from order.models import Order
import datetime


#餐厅申请
@login_required
def restApply(request, success_url=None, template_name="space/customer/rest_apply.html"):
    if request.method == "POST" :
        form = RestApplayForm(request.POST, request.FILES)
        if form.is_valid():
            try:
                restApply = Rest_apply.objects.get(user=request.user)
                form = RestApplayForm(request.POST,request.FILES,instance=restApply)
                form.save()
            except Rest_apply.DoesNotExist:
                restApply = form.save(False)
                restApply.user = request.user
                restApply.user.groups.add(Group.objects.get(name__iexact="rest_apply"))
                restApply.save()
            #return HttpResponseRedirect(success_url or reverse('customer_index'))
            return HttpResponseRedirect(success_url or reverse('customer_index'))
        return render_to_response(template_name,{'form':form},context_instance=RequestContext(request))  
    else:
        restApply = Rest_apply()
        try:
            restApply = Rest_apply.objects.get(user=request.user)
            form = RestApplayForm(instance=restApply)
        except Rest_apply.DoesNotExist:
            form = RestApplayForm(initial={
                                       'user':request.user,
                                       'contact':request.user.first_name+request.user.last_name,
                                       'phone':request.user.username
                                       })
        return render_to_response(template_name,{'form':form,'rest_apply':restApply},context_instance=RequestContext(request))    

@login_required
def customer_orders(request,template_name="space/customer/index.html"):
    mess = {}
    order_trues = Order.objects.filter(user = request.user,state=True).order_by("-mod_date")[0:5] 
    order_falses = Order.objects.filter(user = request.user,state=False).order_by("-mod_date")[0:5]
    consume_rests = Order.objects.filter(user = request.user,state=True).distinct().order_by("-mod_date")[0:5]
    mess['order_trues'] = order_trues
    mess['order_falses'] = order_falses
    mess['consume_rests'] = consume_rests
    return render_to_response(template_name, mess, context_instance=RequestContext(request))
